<template>
  <div class="counseling-records">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="咨询日期">
        <el-date-picker
          v-model="queryParams.consultationTime"
          type="date"
          placeholder="选择日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 记录列表 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>咨询记录列表</span>
        </div>
      </template>
      
      <el-table 
        :data="records" 
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="consultationTime" label="咨询日期" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.consultationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="counselorName" label="咨询师" width="120" />
        <el-table-column prop="duration" label="时长(分钟)" width="100" />
        <el-table-column prop="mainIssue" label="主要问题" show-overflow-tooltip />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">查看</el-button>
            <el-button 
              type="primary" 
              link 
              v-if="canEdit(row)"
              @click="handleEdit(row)"
            >编辑</el-button>
            <el-button
              type="warning"
              link
              v-if="isStudent && !row.rating"
              @click="handleRate(row)"
            >评分</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="records.length"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 详情/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'edit' ? '编辑记录' : '记录详情'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="recordForm"
        :rules="rules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <!-- 添加隐藏的 id 字段 -->
        <el-form-item prop="id" style="display: none;">
          <el-input v-model="recordForm.id" type="hidden" />
        </el-form-item>
        
        <el-form-item label="主要问题" prop="mainIssue">
          <el-input 
            v-model="recordForm.mainIssue" 
            type="textarea" 
            :rows="3"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="问题分析" prop="analysis">
          <el-input 
            v-model="recordForm.analysis"
            type="textarea" 
            :rows="4"
            :maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="建议" prop="suggestion">
          <el-input 
            v-model="recordForm.suggestion" 
            type="textarea" 
            :rows="3"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="后续计划" prop="nextPlan">
          <el-input 
            v-model="recordForm.nextPlan" 
            type="textarea" 
            :rows="3"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="submitLoading"
            v-if="dialogType !== 'view'"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog
      v-model="rateDialogVisible"
      title="咨询评分"
      width="400px"
    >
      <el-form
        ref="rateFormRef"
        :model="rateForm"
        label-width="80px"
      >
        <el-form-item label="评分">
          <el-rate
            v-model="rateForm.rating"
            :max="5"
            show-score
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRating" :loading="rateLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { getRecordList } from '@/api/counseling'
import { formatDateTime } from '@/utils/format'
import request from '@/utils/request'

const store = useStore()

// 角色判断
const isCounselor = computed(() => store.state.user.role === 'counselor')
const isStudent = computed(() => store.state.user.role === 'student')

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  consultationTime: ''
})

// 列表数据
const loading = ref(false)
const total = ref(0)
const records = ref([])

// 记录相关
const dialogVisible = ref(false)
const dialogType = ref<'edit' | 'view'>('view')
const submitLoading = ref(false)

// 评分相关
const rateDialogVisible = ref(false)
const rateLoading = ref(false)
const rateForm = ref({
  counselorId: '',
  rating: 5
})

// 修改表单定义，使用接口定义类型
interface RecordForm {
  id: string | number
  mainIssue: string
  analysis: string
  suggestion: string
  nextPlan: string
}

// 使用类型定义初始化表单
const recordForm = ref<RecordForm>({
  id: '',
  mainIssue: '',
  analysis: '',
  suggestion: '',
  nextPlan: ''
})

// 添加表单验证规则
const rules = ref({
  mainIssue: [{ required: true, message: '请输入主要问题', trigger: 'blur' }],
  analysis: [{ required: true, message: '请输入问题分析', trigger: 'blur' }],
  suggestion: [{ required: true, message: '请输入建议', trigger: 'blur' }]
})

// 表单引用
const formRef = ref()
const rateFormRef = ref()

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getRecordList(queryParams.value)
    console.log('获取到的记录列表:', data.records)
    records.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取咨询记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    consultationTime: ''
  }
  getList()
}

// 查看详情
const handleDetail = (row: any) => {
  dialogType.value = 'view'
  console.log('查看的原始数据:', row)
  
  // 使用解构赋值确保所有字段都被正确复制
  const { id, mainIssue, analysis, suggestion, nextPlan } = row
  
  // 直接赋值整个对象
  recordForm.value = {
    id,  // 直接使用解构出来的id
    mainIssue: mainIssue || '',
    analysis: analysis || '',
    suggestion: suggestion || '',
    nextPlan: nextPlan || ''
  }
  
  console.log('设置到表单的数据:', recordForm.value)
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  console.log('编辑的原始数据:', row)
  
  // 使用解构赋值确保所有字段都被正确复制
  const { id, mainIssue, analysis, suggestion, nextPlan } = row
  
  // 直接赋值整个对象
  recordForm.value = {
    id,  // 直接使用解构出来的id
    mainIssue: mainIssue || '',
    analysis: analysis || '',
    suggestion: suggestion || '',
    nextPlan: nextPlan || ''
  }
  
  console.log('设置到表单的数据:', recordForm.value)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  submitLoading.value = true
  try {
    console.log('提交前的表单数据:', recordForm.value)
    
    // 使用解构赋值创建提交数据
    const { id, mainIssue, analysis, suggestion, nextPlan } = recordForm.value
    
    const submitData = {
      id,  // 直接使用解构出来的id
      mainIssue,
      analysis,
      suggestion,
      nextPlan
    }
    
    console.log('最终提交的数据:', submitData)
    
    await request({
      url: '/record/update',
      method: 'put',
      data: submitData
    })
    ElMessage.success('更新成功')
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('保存失败')
  } finally {
    submitLoading.value = false
  }
}

// 权限控制
const canEdit = (row: any) => {
  return isCounselor.value
}

// 分页处理
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val
  getList()
}

// 处理评分
const handleRate = (row: any) => {
  rateForm.value = {
    counselorId: row.counselorId,
    rating: 5
  }
  rateDialogVisible.value = true
}

// 提交评分
const submitRating = async () => {
  rateLoading.value = true
  try {
    await request({
      url: '/record/rate',
      method: 'post',
      data: rateForm.value
    })
    ElMessage.success('评分成功')
    rateDialogVisible.value = false
    getList() // 刷新列表
  } catch (error) {
    console.error('评分失败:', error)
    ElMessage.error('评分失败')
  } finally {
    rateLoading.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.counseling-records {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .box-card {
    margin-top: 20px;
  }

  .el-table {
    margin-bottom: 20px;
  }
}
</style> 